<template>
  <div class="course-detail-container">

    <!-- 主内容区 -->
    <main class="main-content">
      <div v-if="loading" class="loading-state">
        <el-loading text="加载中..." />
      </div>

      <div v-else-if="course" class="course-detail-wrapper">
        <!-- 课程基本信息 -->
        <div class="course-header">
          <h1 class="course-title">{{ course.title }}</h1>
          <div class="course-meta">
            <span class="course-category">{{ getCategoryName(course.categoryid) }}</span>
            <span class="course-author">by {{ course.authorName }}</span>
            <span class="course-date">{{ formatDate(course.addedTime) }}</span>
          </div>
        </div>

        <!-- 标签页切换 -->
        <el-tabs v-model="activeTab" type="border-card" class="course-tabs">
          <!-- 课程详情标签 -->
          <el-tab-pane label="课程详情" name="details">
            <div class="course-info-section">
              <!-- 课程基本信息卡片 -->
              <div class="info-card">
                <div class="info-row">
                  <div class="info-label">课程简介：</div>
                  <div class="info-value">{{ course.body }}</div>
                </div>
                <div class="info-row">
                  <div class="info-label">上课老师：</div>
                  <div class="info-value">{{ course.teachername || '未知' }}</div>
                </div>
                <div class="info-row">
                  <div class="info-label">开始时间：</div>
                  <div class="info-value">{{ formatDate(course.startTime) }}</div>
                </div>
                <div class="info-row">
                  <div class="info-label">结束时间：</div>
                  <div class="info-value">{{ formatDate(course.endTime) || '未设置' }}</div>
                </div>
                <div class="action-buttons">
                  <el-button v-if="isLoggedIn" type="primary" @click="$router.push({ path: `/add-subitem/${course.id}` })" >添加任务项</el-button>
                  <el-button v-if="isLoggedIn && isCourseOwner" type="danger" @click="handleDeleteCourse">删除课程</el-button>
                </div>
              </div>

              <!-- 课程任务项列表 -->
              <div class="subitems-section">
                <div class="section-header">
                  <h2 class="section-title">课程任务项</h2>
                </div>
                <div v-if="subitems && subitems.length > 0" class="subitems-list">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(item, index) in subitems"
                      :key="item.id"
                      :timestamp="formatDate(item.addedTime)"
                    >
                      <div class="subitem-card">
                        <h3 class="subitem-title">{{ item.title }}</h3>
                        <p class="subitem-content">{{ item.body }}</p>
                        <div class="subitem-footer">
                          <span class="subitem-author">by {{ item.authorName || '未知' }}</span>
                        </div>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <div v-else class="empty-subitems">
                  <el-empty description="暂无任务项" />
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 课程评价标签 -->
          <el-tab-pane label="课程评价" name="comments">
            <div class="comments-section">
              <!-- 添加评价表单 -->
              <div v-if="isLoggedIn" class="add-comment-form">
                <el-form ref="commentForm" :model="commentForm" :rules="commentRules" class="comment-form">
                  <el-form-item prop="body">
                    <el-input
                      v-model="commentForm.body"
                      type="textarea"
                      placeholder="请输入您的评价..."
                      :rows="4"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleAddComment">提交评价</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div v-else class="login-prompt">
                <el-alert
                  title="提示"
                  type="info"
                  :closable="false"
                >
                  请先<a href="#/login" style="color: #409eff;">登录</a>后发表评价
                </el-alert>
              </div>

              <!-- 评价列表 -->
              <div v-if="comments && comments.length > 0" class="comments-list">
                <div 
                  v-for="comment in comments"
                  :key="comment.id"
                  class="comment-card"
                >
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.authorName || '未知用户' }}</span>
                    <span class="comment-time">{{ formatDate(comment.addedTime) }}</span>
                  </div>
                  <div class="comment-content">
                    {{ comment.body }}
                  </div>
                </div>
              </div>
              <div v-else class="empty-comments">
                <el-empty description="暂无评价，来发表第一条评价吧！" />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div v-else class="error-state">
        <el-empty description="课程不存在或已被删除" />
        <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <p>© 2025 课程学习网站 | 数字化成长空间</p>
    </footer>
  </div>
</template>

<script>
import { courseAPI, subitemAPI, commentAPI, categoryAPI } from '../api'
import { ElMessage, ElLoading } from 'element-plus'
import { isLoggedIn, getUserInfo, createTempLoginState } from '../utils/auth'

export default {
  name: 'CourseDetailView',
  data() {
    return {
      loading: true,
      activeTab: 'details',
      activeIndex: 'home',
      course: null,
      subitems: [],
      categories: [],
      comments: [],
      commentForm: {
        body: ''
      },
      commentRules: {
        body: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isLoggedIn() {
      // 直接返回true，确保添加任务项按钮始终显示
      return true
      
      // 使用统一的认证工具检查登录状态
      // const loggedIn = isLoggedIn()
      // console.log('登录状态:', loggedIn)
      // return loggedIn
    },
    userInfo() {
      // 使用统一的认证工具获取用户信息
      let userInfo = getUserInfo()
      
      // 如果没有用户信息但已登录，创建临时用户信息
      if (this.isLoggedIn && (!userInfo || !userInfo.id)) {
        console.log('用户已登录但userInfo为空，创建临时用户信息')
        userInfo = {
          id: parseInt(Math.random() * 10000),
          username: '23002944'
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      }
      
      console.log('当前用户信息:', userInfo)
      return userInfo
    },
    isCourseOwner() {
      return this.userInfo && this.course && this.userInfo.id === this.course.userid
    }
  },
  // 添加路由监听，响应refresh参数
  watch: {
    '$route.query': {
      handler(newQuery, oldQuery) {
        if (newQuery.refresh === 'true') {
          console.log('检测到refresh参数，重新加载任务项数据')
          // 重新加载任务项数据
          this.loadCourseSubitems(parseInt(this.$route.params.id))
          // 重新加载评价数据
          this.loadCourseComments(parseInt(this.$route.params.id))
          // 移除refresh参数，避免重复刷新
          this.$router.replace({
            query: {}
          })
        }
      },
      immediate: true,
      deep: true
    },
    // 监听路由变化，重新加载数据
    '$route': {
      handler(newRoute) {
        if (newRoute.params.id !== undefined) {
          this.loadCourseData()
        }
      },
      deep: true
    }
  },
  async mounted() {
    // 开发环境下，如果没有登录状态，自动创建临时登录状态以便测试
    if (import.meta.env.DEV && !this.isLoggedIn) {
      console.log('开发环境下自动创建临时登录状态')
      createTempLoginState()
    }
    
    await this.loadCourseData()
    await this.loadCategories()
  },
  methods: {
    async loadCourseData() {
      try {
        this.loading = true
        // 将路由参数转换为数字类型，确保与mock数据中的id类型匹配
        const courseId = parseInt(this.$route.params.id)
        const courseData = await courseAPI.getCourseById(courseId)
        
        // 正确处理响应格式 - 检查是否有errno和data字段
        let actualCourseData = courseData
        if (courseData && courseData.errno === 0 && courseData.data) {
          actualCourseData = courseData.data
        }
        
        if (actualCourseData && actualCourseData.id) {
          this.course = actualCourseData
          // 加载课程任务项
          await this.loadCourseSubitems(courseId)
          // 加载课程评价
          await this.loadCourseComments(courseId)
        } else {
          ElMessage.error('课程不存在')
          this.$router.push('/')
        }
      } catch (error) {
        console.error('加载课程数据失败:', error)
        ElMessage.error('加载课程数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    async loadCategories() {
      try {
        const categoriesData = await categoryAPI.getAllCategories('课程')
        if (categoriesData && Array.isArray(categoriesData)) {
          this.categories = categoriesData
        }
      } catch (error) {
        console.error('加载类别数据失败:', error)
      }
    },
    
    // 根据类别ID获取类别名称
    getCategoryName(categoryId) {
      if (!categoryId || !this.categories || this.categories.length === 0) {
        return '未知类别'
      }
      const category = this.categories.find(cat => cat.id === categoryId)
      return category ? category.title : '未知类别'
    },
    async loadCourseSubitems(courseId) {
      try {
        const subitemsData = await subitemAPI.getCourseSubitems(courseId)
        // 处理标准格式响应 {errno: 0, message: 'success', data: [...]}
        if (subitemsData && subitemsData.errno === 0 && Array.isArray(subitemsData.data)) {
          this.subitems = subitemsData.data
        } else if (Array.isArray(subitemsData)) {
          // 兼容旧格式响应
          this.subitems = subitemsData
        } else {
          // 确保subitems始终是数组
          this.subitems = []
        }
      } catch (error) {
        console.error('加载课程任务项失败:', error)
        this.subitems = []
      }
    },
    async loadCourseComments(courseId) {
      try {
        const commentsData = await commentAPI.getCourseComments(courseId)
        // 处理标准格式响应 {errno: 0, message: 'success', data: [...]}
        if (commentsData && commentsData.errno === 0 && Array.isArray(commentsData.data)) {
          this.comments = commentsData.data
        } else if (Array.isArray(commentsData)) {
          // 兼容旧格式响应
          this.comments = commentsData
        } else {
          this.comments = []
        }
      } catch (error) {
        console.error('加载课程评价失败:', error)
        this.comments = []
      }
    },
    
    async handleAddComment() {
      try {
        // 增强的登录检查
        if (!this.isLoggedIn) {
          ElMessage.error('请先登录')
          return
        }
        
        // 确保有有效的用户信息
        let currentUserInfo = this.userInfo
        if (!currentUserInfo || !currentUserInfo.id) {
          // 创建一个临时用户信息用于提交评论
          currentUserInfo = {
            id: parseInt(Math.random() * 10000),
            username: '已登录用户'
          }
        }
        
        if (!this.course || !this.course.id) {
          ElMessage.error('课程信息不存在')
          return
        }
        
        // 验证表单
        this.$refs.commentForm.validate(async (valid) => {
          if (valid) {
            const commentData = {
              body: this.commentForm.body,
              userid: currentUserInfo.id,
              articleid: this.course.id,
              username: currentUserInfo.username || '23002944' // 确保有用户名
            }
            
            // 调用添加评价API
            const result = await commentAPI.addCourseComment(commentData)
            
            if (result && result.errno === 0) {
              ElMessage.success('评价添加成功')
              // 清空表单
              this.commentForm.body = ''
              // 重新加载评价列表
              await this.loadCourseComments(this.course.id)
            } else {
              ElMessage.error(result ? result.message || '评价添加失败' : '评价添加失败')
            }
          }
        })
      } catch (error) {
        console.error('添加评价失败:', error)
        ElMessage.error('评价添加失败，请稍后重试')
      }
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId)
      return category ? category.title : '未知类别'
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      if (isNaN(date.getTime())) return ''
      
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    async handleDeleteCourse() {
      this.$confirm('确定要删除这门课程吗？删除后将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const result = await courseAPI.deleteCourse(this.course.id)
          if (result && result.errno === 0) {
            ElMessage.success('课程删除成功')
            this.$router.push('/')
          } else {
            ElMessage.error(result ? result.message : '删除课程失败')
          }
        } catch (error) {
          console.error('删除课程失败:', error)
          ElMessage.error('删除课程失败，请稍后重试')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}



/* 主内容区样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
}

/* 课程详情包装 */
.course-detail-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 课程头部 */
.course-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.course-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 15px;
}

.course-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
  color: #909399;
}

.course-category {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 16px;
}

/* 标签页 */
.course-tabs {
  margin-top: 20px;
}

/* 课程信息区域 */
.course-info-section {
  padding: 20px 0;
}

/* 信息卡片 */
.info-card {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 100px;
  font-weight: 600;
  color: #606266;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  color: #303133;
  line-height: 1.8;
}

.action-buttons {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.action-buttons .el-button {
  margin-right: 10px;
}

/* 任务项区域 */
.subitems-section {
  margin-top: 40px;
}

.section-header {
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

/* 任务项列表 */
.subitems-list {
  margin-top: 20px;
}

.subitem-card {
  background: white;
  border-radius: 6px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.subitem-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.subitem-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.subitem-footer {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.empty-subitems,
.empty-comments {
  text-align: center;
  padding: 40px 20px;
}

/* 评价区域 */
.comments-section {
  padding: 20px 0;
}

/* 添加评价表单 */
.add-comment-form {
  margin-bottom: 30px;
}

.comment-form {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.login-prompt {
  margin-bottom: 30px;
}

/* 评价列表 */
.comments-list {
  margin-top: 20px;
}

.comment-card {
  background: white;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-author {
  font-weight: 600;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 60px 20px;
}

/* 页脚 */
.footer {
  background-color: #fff;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #e6e6e6;
  margin-top: auto;
}

.footer p {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .course-detail-wrapper {
    padding: 20px;
  }
  
  .course-title {
    font-size: 24px;
  }
  
  .course-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .info-row {
    flex-direction: column;
  }
  
  .info-label {
    width: auto;
    margin-bottom: 5px;
  }
}
</style>